<template>
	<el-dialog v-model="dialogVisible" :title="id ? '修改等级' : '新建等级'" width="900px">
		<el-form label-width="100px" ref="formRef" :model="diaForm">
			<el-form-item label="当前科目">
				<el-input v-model="currentSubject.subjectName" disabled />
			</el-form-item>
			<el-form-item label="等级名称" prop="gradeName">
				<el-input v-model="diaForm.gradeName" placeholder="请输入等级名称" />
			</el-form-item>
			<el-form-item label="价格" prop="amount">
				<el-input v-model.number="diaForm.amount" :min='0' placeholder="请输入价格"></el-input>
			</el-form-item>
			<el-form-item label="状态" prop="enabled" class="inline">
				<el-radio-group v-model="diaForm.enabled">
					<el-radio v-for="item in dicts.system_global_status" :key="item.k" :label="Number(item.v)"
						:value="item.v">
						{{ item.k }}
					</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="协议" prop="protocol">
				<div style="width: 100%">
					<!-- 富文本组件 -->
					<wangEditor v-model="diaForm.protocol" />
				</div>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="onSubmit">保存</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import wangEditor from '@renderer/components/wangEditor/wangEditor.vue'
import { getGradeGetApi, postGradeAOUApi } from '@renderer/api/grade';
import { GradeForm } from '@renderer/interface/grade';
import { useDicts } from '@renderer/composables/dicts';
import { SubjectItem } from '@renderer/interface/subject';

/* 父组件传参 */
const props = defineProps<{
	// 等级id
	id: string,
	// 当前科目信息
	currentSubject: SubjectItem
}>()
const emits = defineEmits(['addSuccess'])
const dialogVisible = defineModel({ default: false })

// 表单数据
const diaFormValue = (): GradeForm => ({
	subjectId: '',
	gradeName: '',
	amount: '',
	protocol: '',
	enabled: '',
})
const diaForm = ref<GradeForm>(diaFormValue())
const { dicts } = useDicts(['system_global_status'])
// 获取表单数据
const getDiaFormData = async () => {
	const { code, data } = await getGradeGetApi(props.id)
	if (code !== '200') return

	diaForm.value = data
}

//添加等级
const postGradeAOUData = async () => {
	const { code } = await postGradeAOUApi(diaForm.value)
	if (code !== '200') return

	ElMessage({
		type: 'success',
		message: props.id ? '修改等级成功~' : '添加等级成功~'
	})
	dialogVisible.value = false

	// 通知父组件
	emits('addSuccess')
}
//确认
const onSubmit = async () => {
	postGradeAOUData()
	dialogVisible.value = false
	emits('addSuccess');
}

watch(dialogVisible, () => {
	if (dialogVisible.value) {
		// 打开 dialog 时获取数据
		if (props.id) {
			getDiaFormData()
		} else {
			diaForm.value.subjectId = props.currentSubject.id
		}
	} else {
		// 关闭 dialog 时清空数据
		diaForm.value = diaFormValue()
	}
})
</script>